using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
//using CYZHAPI.Common.Config;
using CYZHAPI.Common;
using CYZHAPI.Common.Config;
using CYZHAPI.Common.tools;
using CYZHAPI.Entity;
using CYZHAPI.IRepository;
using CYZHAPI.IRepository.IService;
//using CYZHAPI.Repository;
using CYZHAPI.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CYZHAPI.Controllers
{
    //[Route("api/[controller]")]
    //[EnableCors(WebApiOption.CORS_POLICY_NAME)] //设置跨域处理的 代理
    public class loginController : BaseController
    {
        private IUserLoginService _IUserLoginService; 
        private IMemoryCache _memoryCache;
        private WebApiOption _webapiOption;
        public loginController(IUserLoginService objUserLoginService, IMemoryCache memoryCache,IOptions<WebApiOption> options , ILogger<loginController> logger) : base(logger)
        {
            _IUserLoginService = objUserLoginService;
            _memoryCache = memoryCache;
            _webapiOption = options.Value;
        }
        // GET api/login
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/login/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }


        // POST api/login
        [HttpPost]
        public cookieinfo Post([FromBody]Userbean objUser)
        {
           // Userbean objUser = new Userbean();
            string result;
            string randomValue = cryptionTool.GetRandomString(10, true, true, true, false, "");
            cookieinfo strCookie = _IUserLoginService.get(objUser.username, objUser.password, randomValue);
            if (strCookie.code.Equals("200"))
            {
                string cachekey =
                    cryptionTool.DesEncrypt(_webapiOption.Cors.Original + '|' + objUser.username, randomValue);
                string cookieKey = cachekey+'|'+randomValue;
                strCookie.cookieid = cryptionTool.DesEncrypt(cookieKey);
                bool createCache = _memoryCache.TryGetValue(cachekey, out result);
                if (!createCache)
                {
                    long cookieTime = _webapiOption.Cors.Cookietime*60*1000;
                    strCookie.cookietime = cookieTime;
                    _memoryCache.Set(cachekey, strCookie.cookieValue, new MemoryCacheEntryOptions()
                        .SetAbsoluteExpiration(TimeSpan.FromMinutes(cookieTime)));
                    strCookie.cookieValue = "";
                    //createCache = _memoryCache.TryGetValue(strCookie.cookieid, out result);
                }
            }
            
            return strCookie;
        }
    }
}